package org.example.sys.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import org.example.core.web.PageResult;
import org.example.core.web.Result;
import org.example.sys.entity.TSysUser;
import org.example.sys.entity.base.BatchParam;
import org.example.sys.entity.base.ExistenceParam;
import org.example.sys.entity.dto.UserDTO;
import org.example.sys.service.TSysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 用户表(TSysUser)表控制层
 * @author Calvin
 */
@RestController
@RequestMapping("/api/system/user")
public class TSysUserController extends ApiController {
    /**
     * 服务对象
     */
    @Resource
    private TSysUserService tSysUserService;

    /**
     * 分页查询所有数据
     * @param page     分页对象
     * @param tSysUser 查询实体
     * @return 所有数据
     */
    @PreAuthorize("hasAuthority('sys:user:list')")
    @GetMapping("/page")
    public Result<PageResult<TSysUser>> page(Page<TSysUser> page, TSysUser tSysUser) {
        return success(this.tSysUserService.page(page, new QueryWrapper<>(tSysUser)));
    }

    /**
     * 查询所有数据
     * @param page     分页对象
     * @param tSysUser 查询实体
     * @return 所有数据
     */
    @PreAuthorize("hasAuthority('sys:user:list')")
    @GetMapping()
    public Result<List<TSysUser>> list(Page<TSysUser> page, TSysUser tSysUser) {
        return success(this.tSysUserService.list(page, new QueryWrapper<>(tSysUser)));
    }

    /**
     * 通过主键查询单条数据
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/{id}")
    public Result<UserDTO> getByIdRel(@PathVariable Long id) {
        return success(this.tSysUserService.getByIdRel(id));
    }

    /**
     * 新增数据
     * @param user 实体对象
     * @return 新增结果
     */
    @PreAuthorize("hasAuthority('sys:user:save')")
    @PostMapping()
    public Result<?> add(@RequestBody UserDTO user) {
        user.setStatus(0);
        user.setPassword(tSysUserService.encodePassword(user.getPassword()));
        if (tSysUserService.saveUser(user)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('sys:user:update')")
    @PutMapping()
    public Result<?> update(@RequestBody UserDTO user) {
        user.setStatus(null);
        user.setUsername(null);
        user.setPassword(null);
        if (tSysUserService.updateUser(user)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('sys:user:remove')")
    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")
    public Result<?> remove(@PathVariable("id") Integer id) {
        if (tSysUserService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('sys:user:remove')")
    @Operation(summary = "批量删除用户")
    //@ApiImplicitParams({
    //@ApiImplicitParam(name = "ids", value = "id数组", required = true, dataType = "string")
    //})
    @Parameters({@Parameter(name = "ids",description = "id数组",required = true)})
    @DeleteMapping("/batch")
    public Result<?> deleteBatch(@RequestBody List<Integer> ids) {
        if (tSysUserService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('sys:user:update')")
    @Operation(summary = "批量修改用户")
    @PutMapping("/batch")
    public Result<?> removeBatch(@RequestBody BatchParam<TSysUser> batchParam) {
        if (batchParam.update(tSysUserService, TSysUser::getUserId)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('sys:user:update')")
    @Operation(summary = "修改用户状态")
    @PutMapping("/status")
    public Result<?> updateStatus(@RequestBody UserDTO user) {
        if (user.getUserId() == null || user.getStatus() == null || !Arrays.asList(0, 1).contains(user.getStatus())) {
            return fail("参数不正确");
        }
        UserDTO u = new UserDTO();
        u.setUserId(user.getUserId());
        u.setStatus(user.getStatus());
        if (tSysUserService.updateById(u)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('sys:user:update')")
    @Operation(summary = "批量修改用户状态")
    @PutMapping("/status/batch")
    public Result<?> updateStatusBatch(@RequestBody BatchParam<Integer> batchParam) {
        if (!Arrays.asList(0, 1).contains(batchParam.getData())) {
            return fail("状态值不正确");
        }
        if (tSysUserService.update(new LambdaUpdateWrapper<TSysUser>()
                .in(TSysUser::getUserId, batchParam.getIds())
                .set(TSysUser::getStatus, batchParam.getData()))) {
            return success("修改成功");
        }
        return fail("修改失败");
    }


    @PreAuthorize("hasAuthority('sys:user:update')")
    @Operation(summary = "重置密码")
    @PutMapping("/password")
    public Result<?> resetPassword(@RequestBody UserDTO user) {
        if (user.getUserId() == null || StrUtil.isBlank(user.getPassword())) {
            return fail("参数不正确");
        }
        UserDTO u = new UserDTO();
        u.setUserId(user.getUserId());
        u.setPassword(tSysUserService.encodePassword(user.getPassword()));
        if (tSysUserService.updateById(u)) {
            return success("重置成功");
        } else {
            return fail("重置失败");
        }
    }

    @PreAuthorize("hasAuthority('sys:user:update')")
    @Operation(summary = "批量重置密码")
    @PutMapping("/password/batch")
    public Result<?> resetPasswordBatch(@RequestBody BatchParam<String> batchParam) {
        if (batchParam.getIds() == null || batchParam.getIds().size() == 0) {
            return fail("请选择用户");
        }
        if (batchParam.getData() == null) {
            return fail("请输入密码");
        }
        if (tSysUserService.update(new LambdaUpdateWrapper<TSysUser>()
                .in(TSysUser::getUserId, batchParam.getIds())
                .set(TSysUser::getPassword, tSysUserService.encodePassword(batchParam.getData())))) {
            return success("重置成功");
        } else {
            return fail("重置失败");
        }
    }

    @PreAuthorize("hasAuthority('sys:user:list')")
    @Operation(summary = "检查用户是否存在")
    @GetMapping("/existence")
    public Result<?> existence(ExistenceParam<TSysUser> param) {
        if (param.isExistence(tSysUserService, TSysUser::getUserId)) {
            return success(param.getValue() + "已存在");
        }
        return fail(param.getValue() + "不存在");
    }

    /**
     * excel导入用户
     */
//    @PreAuthorize("hasAuthority('sys:user:save')")
//    @Operation(summary = "导入用户")
//    @Transactional(rollbackFor = {Exception.class})
//    @PostMapping("/import")
//    public Result<List<String>> importBatch(MultipartFile file) {
//        ImportParams importParams = new ImportParams();
//        try {
//            List<UserImportParam> list = ExcelImportUtil.importExcel(file.getInputStream(),
//                    UserImportParam.class, importParams);
//            // 校验是否重复
//            if (CommonUtil.checkRepeat(list, UserImportParam::getUsername)) {
//                return fail("账号存在重复", null);
//            }
//            if (CommonUtil.checkRepeat(list, UserImportParam::getPhone)) {
//                return fail("手机号存在重复", null);
//            }
//            // 校验是否存在
//            List<TSysUser> usernameExists = tSysUserService.list(new LambdaQueryWrapper<TSysUser>().in(TSysUser::getUsername,
//                    list.stream().map(UserImportParam::getUsername).collect(Collectors.toList())));
//            if (usernameExists.size() > 0) {
//                return fail("账号已经存在",
//                        usernameExists.stream().map(TSysUser::getUsername).collect(Collectors.toList()));
//            }
//            List<TSysUser> phoneExists = tSysUserService.list(new LambdaQueryWrapper<TSysUser>().in(TSysUser::getPhone,
//                    list.stream().map(UserImportParam::getPhone).collect(Collectors.toList())));
//            if (phoneExists.size() > 0) {
//                return fail("手机号已经存在",
//                        phoneExists.stream().map(User::getPhone).collect(Collectors.toList()));
//            }
//            // 添加
//            List<TSysUser> users = new ArrayList<>();
//            for (UserImportParam one : list) {
//                TSysUser u = new TSysUser();
//                u.setStatus(0);
//                u.setUsername(one.getUsername());
//                u.setPassword(userService.encodePassword(one.getPassword()));
//                u.setNickname(one.getNickname());
//                u.setPhone(one.getPhone());
//                Role role = roleService.getOne(new QueryWrapper<Role>()
//                        .eq("role_name", one.getRoleName()), false);
//                if (role == null) {
//                    return fail("角色不存在", Collections.singletonList(one.getRoleName()));
//                } else {
//                    u.setRoles(Collections.singletonList(role));
//                }
//                Organization organization = organizationService.getOne(new QueryWrapper<Organization>()
//                        .eq("organization_full_name", one.getOrganizationName()), false);
//                if (organization == null) {
//                    return fail("机构不存在", Collections.singletonList(one.getOrganizationName()));
//                } else {
//                    u.setOrganizationId(organization.getOrganizationId());
//                }
//                DictionaryData sex = dictionaryDataService.getByDictCodeAndName("sex", one.getSexName());
//                if (sex == null) {
//                    return fail("性别不存在", Collections.singletonList(one.getSexName()));
//                } else {
//                    u.setSex(sex.getDictDataCode());
//                }
//            }
//            if (tSysUserService.saveBatch(users)) {
//                return success("导入成功", null);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return fail("导入失败", null);
//    }

}

